package com.douding.file.controller.admin;

import com.douding.server.domain.Test;
import com.douding.server.dto.FileDto;
import com.douding.server.dto.ResponseDto;
import com.douding.server.enums.FileUseEnum;
import com.douding.server.exception.BusinessException;
import com.douding.server.service.FileService;
import com.douding.server.service.TestService;
import com.douding.server.util.Base64ToMultipartFile;
import com.douding.server.util.UuidUtil;
import com.mysql.cj.util.Base64Decoder;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.util.List;

/*
    返回json 应用@RestController
    返回页面  用用@Controller
 */
@RequestMapping("/admin/file")
@RestController
public class UploadController {

    private static final Logger LOG = LoggerFactory.getLogger(UploadController.class);
    public  static final String BUSINESS_NAME ="文件上传";
    @Resource
    private TestService testService;

    @Value("${file.path}")
    private String FILE_PATH;

    @Value("${file.domain}")
    private String FILE_DOMAIN;

    @Resource
    private FileService fileService;

    @RequestMapping("/upload")
    public ResponseDto upload(@RequestBody FileDto fileDto) throws Exception {
        LOG.info("上传分片");
        fileDto.setPath("teacher/"+fileDto.getName());
        merge(fileDto);
        ResponseDto responseDto = new ResponseDto<FileDto>();
        fileDto.setPath(FILE_DOMAIN+fileDto.getPath());
        responseDto.setContent(fileDto);
        return responseDto;
    }

    //合并分片
    public void merge(FileDto fileDto) throws Exception {
        LOG.info("合并分片开始");
        String base64 = fileDto.getShard();
        base64 = base64.split(",")[1];
        byte[] decode = DatatypeConverter.parseBase64Binary(base64);
        int length = decode.length;
        for(int i=0;i<length;++i){
            if(decode[i] < 0){
                decode[i] += 256;
            }
        }
        try (
                FileOutputStream fileOutputStream = new FileOutputStream(FILE_PATH+fileDto.getPath(),true)
                ){
            fileOutputStream.write(decode);
            fileOutputStream.flush();

            fileService.save(fileDto);
        }catch (Exception e){
            e.printStackTrace();
            LOG.warn("分片合并失败");
        }
    }

    @GetMapping("/check/{key}")
    public ResponseDto check(@PathVariable String key) throws Exception {
        LOG.info("检查上传分片开始：{}", key);
        ResponseDto<FileDto> responseDto = new ResponseDto<>();
        responseDto.setContent(fileService.findByKey(key));
        return responseDto;
    }

}//end class
